//
//  COGiftContent.swift
//  CocoProject
//
//  Created by Vill on 2023/11/10.
//

import UIKit
import SwiftyJSON

class COGiftContent: RCMessageContent {

    var id: String?             // 礼物ID
    var name: String?           // 礼物名称
    var cover: String?          // 礼物图
    var fileUrl: String?        // 礼物链接
    var count: Int?             // 礼物数量
    var toStreamerName: String? // 发送对象
    
    override class func persistentFlag() -> RCMessagePersistent {
        return .MessagePersistent_ISCOUNTED
    }
    
    override func conversationDigest() -> String? {
        return "[\(self.name ?? "Gift")]"
    }
    
    override class func getObjectName() -> String {
        return "RC:GiftMsg"
    }
    
    override func encode() -> Data? {
        var dataDict = [String: Any]()
        if let senderUserInfo = self.senderUserInfo {
            var userInfoDict = [String: String]()
            userInfoDict["userId"] = senderUserInfo.userId
            userInfoDict["name"] = senderUserInfo.name
            userInfoDict["portraitUri"] = senderUserInfo.portraitUri
            dataDict["user"] = userInfoDict
        }
        dataDict["id"] = id
        dataDict["name"] = name
        dataDict["cover"] = cover
        dataDict["fileUrl"] = fileUrl
        dataDict["count"] = count
        dataDict["toStreamerName"] = toStreamerName
        
        if let data = try? JSONSerialization.data(withJSONObject: dataDict, options: []) {
            return data
        }
        return nil
    }
    
    override func decode(with data: Data) {
        if let dict = try? JSONSerialization.jsonObject(with: data, options: []) {
            let json = JSON(dict)
            id = json["id"].string
            name = json["name"].string
            cover = json["cover"].string
            fileUrl = json["fileUrl"].string
            count = json["count"].int
            toStreamerName = json["toStreamerName"].string
            
            if let user = json["user"].dictionary {
                let userInfo = RCUserInfo()
                userInfo.name = user["name"]?.string ?? ""
                if let portraitUri = user["portraitUri"]?.string {
                    userInfo.portraitUri = portraitUri
                }else {
                    userInfo.portraitUri = user["portrait"]?.string
                }
                if let userId = user["userId"]?.string {
                    userInfo.userId = userId
                }else {
                    userInfo.userId = user["id"]?.string ?? ""
                }
                self.senderUserInfo = userInfo
            }
        }
    }
    
}
